package com.tanhua.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.mongodb.client.result.UpdateResult;
import com.tanhua.sso.pojo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.Date;
import java.util.List;

@DubboService
public class UserLikeServiceApiImpi implements UserLikeServiceApi{

    @Autowired
    private MongoTemplate mongoTemplate;

   // 添加或修改好友是否喜欢
    @Override
    public boolean save(Long userId, Long likeUserId, boolean flag) {
        Criteria criteria = Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId);
        boolean exists = mongoTemplate.exists(Query.query(criteria), UserLike.class);
        //存在,并修改
        if (exists){
            Update update=new Update();
            //修改喜欢并更新时间
            update.set("isLike", flag).set("updated",System.currentTimeMillis());
            UpdateResult result = mongoTemplate.updateFirst(Query.query(criteria), update, UserLike.class);
            //判断是否修改成功
            if (ObjectUtil.isEmpty(result)){
                return false;
            }
            //不存在,则添加
        }else {
            UserLike userLike=new UserLike();
            userLike.setIsLike(flag);
            userLike.setLikeUserId(likeUserId);
            userLike.setUserId(userId);
            userLike.setCreated(System.currentTimeMillis());
            userLike.setUpdated(System.currentTimeMillis());
            UserLike save = mongoTemplate.save(userLike);
            if (ObjectUtil.isEmpty(save)){
                return false;
            }
        }
        return true;
    }

    //判断她是否喜欢你
    @Override
    public boolean isLike(Long userId, Long likeUserId, boolean like) {
        Criteria criteria = Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId).and("isLike").is(like);
        boolean exists = mongoTemplate.exists(Query.query(criteria), UserLike.class);
        return exists;
    }

    //查看我喜欢的人
    @Override
    public List<UserLike> likeAll(Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId).and("isLike").is(true);
        List<UserLike> likes = mongoTemplate.find(Query.query(criteria).with(Sort.by(Sort.Order.desc("created"))), UserLike.class);
        return likes;
    }
}
